#include "client.h"

int main(int argc, char** argv) {
  int c;
  int udp = 0;
  char *server;
  int port = DEFAULTPORT;

  opterr = 0;
  
  while ((c = getopt(argc, argv, "up:s:")) != -1) {
    switch(c) {
      case 'u':
        udp = 1;
        break;
      case 'd':
        port = atoi(optarg);
        break;
      case 's':
      	server = optarg;
      	break;
      case '?':
        if (optopt == 'p' || optopt == 's')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr, "Unknown option character `\\x%x'.\n",optopt);
             return 1;
      default:
        usage();
    }
  }
  
  if (port == 0)
  {
  	fprintf(stderr, "Invalid port\n");
  	usage();
  }
  return (0);
}

void usage() {

}

void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET) {
        return &(((struct sockaddr_in*)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

int connect_to_server(char *server, int port) {
    int sockfd, numbytes;  
    struct addrinfo hints, *servinfo, *p;
    int rv;
    char s[INET6_ADDRSTRLEN];

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ((rv = getaddrinfo(server, port, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and connect to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("client: socket");
            continue;
        }

        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("client: connect");
            continue;
        }

        break;
    }

    if (p == NULL) {
        fprintf(stderr, "client: failed to connect\n");
        return 2;
    }

    inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
            s, sizeof s);
    printf("client: connecting to %s\n", s);

    freeaddrinfo(servinfo); // all done with this structure

    shell(sockfd);
    close(sockfd);

    return 0;
}


int shell(int sock) {
	char command[MAX_COMMAND_LENGHT];
	int quit, ret;
	char *cwd, *pwd;

	cwd = getcwd(NULL);
	pwd = getcwd(NULL);
	for(quit = 0;quit == 0 ;) {
		fprintf(stdout, "%s %s", cwd, PROMPT);
		if (fgets(command, MAX_COMMAND_LENGHT, stdin) != NULL) {
			ret = check_command(command, sock, &quit);
		} else {
			perror("Error reading command");
			return 1;
		}
		pwd = getcwd(pwd);
	}
	chdir(cwd);
	free(cwd);
	free(pwd);
	return 0;
}
